package com.iwunu.auth.util;

import org.apache.commons.lang3.Validate;

import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;

/**
 * 加密；验证密码
 * @author: vivi207
 * @create: 2018/5/9 11:41
 **/
public class DigestsUtils2 {
    private static final String SHA1 = "SHA-1";
    public static final int SALT_SIZE = 8;
    public static final int HASH_INTERATIONS = 1024;

    private static SecureRandom random = new SecureRandom();

    public static byte[] sha1(byte[] input, byte[] salt, int iterations) {
        return digest(input, SHA1, salt, iterations);
    }

    /**
     * 对字符串进行散列, 支持md5与sha1算法.
     */
    private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) {
        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);

            if (salt != null) {
                digest.update(salt);
            }

            byte[] result = digest.digest(input);

            for (int i = 1; i < iterations; i++) {
                digest.reset();
                result = digest.digest(result);
            }
            return result;
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 生成随机的Byte[]作为salt.
     *
     * @param numBytes byte数组的大小
     */
    public static byte[] generateSalt(int numBytes) {
        Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes);

        byte[] bytes = new byte[numBytes];
        random.nextBytes(bytes);
        return bytes;
    }

    /**
     * 生成安全的密码，生成随机的16位salt并经过1024次 sha-1 hash
     */
    public static String entryptPassword(String plainPassword) {
        byte[] salt = generateSalt(SALT_SIZE);
        byte[] hashPassword = sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
        return EncodesUtils.encodeHex(salt)+EncodesUtils.encodeHex(hashPassword);
    }

    /**
     * 验证密码
     * @param plainPassword 明文密码
     * @param password 密文密码
     * @return 验证成功返回true
     */
    public static boolean validatePassword(String plainPassword, String password) {
        byte[] salt = EncodesUtils.decodeHex(password.substring(0,16));
        byte[] hashPassword = sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
        return password.equals(EncodesUtils.encodeHex(salt)+EncodesUtils.encodeHex(hashPassword));
    }

    public static void main(String[] args) {
        System.out.println(entryptPassword("yzaan"));
        System.out.println(validatePassword("yzaan1", "23c4c2a35ea235ae576b12748ce0bde4f1c5f5102d8da2a72fbadfe5"));
    }
}
